package cn.tedu.knows.sys.service.impl;


import cn.tedu.knows.commons.exception.ServiceException;
import cn.tedu.knows.commons.model.Classroom;
import cn.tedu.knows.commons.model.User;
import cn.tedu.knows.commons.model.UserRole;
import cn.tedu.knows.sys.mapper.ClassroomMapper;
import cn.tedu.knows.sys.mapper.UserMapper;
import cn.tedu.knows.sys.mapper.UserRoleMapper;
import cn.tedu.knows.sys.service.IUserService;
import cn.tedu.knows.sys.vo.RegisterVO;
import cn.tedu.knows.sys.vo.UserVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author tedu.cn
 * @since 2022-03-04
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ClassroomMapper classroomMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;


    @Override
    @Transactional
    public void registerStudent(RegisterVO registerVO) {
        QueryWrapper<Classroom> query = new QueryWrapper<>();
        query.eq("invite_code", registerVO.getInviteCode());
        Classroom classroom = classroomMapper.selectOne(query);
        if (classroom == null) {
            throw new ServiceException("邀请码错误");
        }
        User user = userMapper.findUserByUsername(registerVO.getPhone());
        if (user != null) {
            throw new ServiceException("手机号已经被注册");
        }
        PasswordEncoder encoder = new BCryptPasswordEncoder();
        String pwd = "{bcrypt}" + encoder.encode(registerVO.getPassword());
        User stu = new User()
                .setUsername(registerVO.getPhone())
                .setNickname(registerVO.getNickname())
                .setPassword(pwd)
                .setClassroomId(classroom.getId())
                .setCreatetime(LocalDateTime.now())
                .setEnabled(1)
                .setLocked(0)
                .setType(0);
        int num = userMapper.insert(stu);
        if (num != 1) {
            throw new ServiceException("数据库异常");
        }
        UserRole userRole = new UserRole()
                .setRoleId(2)
                .setUserId(stu.getId());
        num = userRoleMapper.insert(userRole);
        if (num != 1) {
            throw new ServiceException("数据库异常");
        }
    }

    //声明两个讲师缓存的集合
    private List<User> teachers = new CopyOnWriteArrayList<>();
    private Map<String, User> teacherMap = new ConcurrentHashMap<>();

    @Override
    public List<User> getTeachers() {
        if (teachers.isEmpty()) {
            synchronized (teachers) {
                teachers.clear();
                teacherMap.clear();
                List<User> list = userMapper.findTeachers();
                teachers.addAll(list);
                for (User u : list) {
                    teacherMap.put(u.getNickname(), u);
                }
            }
        }
        return teachers;
    }

    @Override
    public Map<String, User> getTeacherMap() {
        if (teacherMap.isEmpty()) {
            getTeachers();
        }
        return teacherMap;
    }


    @Override
    public UserVO getUserVO(String username) {
        User user = userMapper.findUserByUsername(username);

        UserVO userVO = new UserVO()
                .setId(user.getId())
                .setUsername(user.getUsername())
                .setNickname(user.getNickname());
        return userVO;

    }
}
